__author__ = 'Rusher'
import socketserver
import threading
import sys
import time
import http.server

clients = []


class CharRoom(object):
    def __init__(self):
        pass


class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        print(str(self.client_address)+' is trying...')
        # self.request is the TCP socket connected to the client
        global clients
        self.u_flag = ''
        self.username = ''
        clients.append(self)
        while 1:
            try:
                print('new round')
                self.data = self.request.recv(1024).strip()
            except ConnectionResetError:
                print(str(self.client_address)+' quited!')
                break

            # get username
            if not self.u_flag:
                if not self.data.startswith(bytes('!username', 'utf8')):
                    print('not valid!')
                    break
                self.u_flag = 'verified'
                start = self.data.decode('utf8')[1:].find('!')
                self.username = self.data[start+2:].decode('utf8')
                for client in clients:
                    if client is not self and client.username == self.username:
                        self.request.sendall(bytes('!error!username_conflict', 'utf8'))
                        self.u_flag = 'conflict'
                        break
                if self.u_flag == 'conflict':
                    break
                print('Got connection from %s' % str(self.client_address) + ' username: !' + self.username + '!')
                self.request.sendall(bytes('!info!OK', 'utf8'))
                print('continue')
                continue

            if self.data:
                print("{} wrote:".format(self.username))
                print(self.data)
                # just send back the same data, but upper-cased
                for client in clients:
                    if client is not self:
                        print('Sending...')
                        s_msg = '!' + self.username + '!' + self.data.decode('utf8')
                        client.request.sendall(bytes(s_msg, 'utf8'))
                        print(s_msg)
            time.sleep(0.1)
        self.request.close()
        print(str(self.client_address) + 'disconnected.')
        clients.remove(self)


class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
        pass

host = '0.0.0.0'
port = 12345


def http_server():
    Handler = http.server.SimpleHTTPRequestHandler
    httpd = socketserver.TCPServer((host, 12346), Handler)
    httpd.serve_forever()


def main():
    arg = sys.argv
    print(arg)
    if len(arg) == 3:
        host = arg[1]
        port = int(arg[2])
    else:
        host = "0.0.0.0"
        port = 12345

    threading.Thread(target=http_server).start()
    server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
    server.serve_forever()


if __name__ == "__main__":
    main()
